package com.ccteam.shared.domain.user

import com.ccteam.model.Resource
import com.ccteam.network.ApiError
import com.ccteam.network.ApiResult
import com.ccteam.shared.core.UserCore
import com.ccteam.shared.data.user.UserRepository
import com.ccteam.shared.domain.SuspendUseCase
import kotlinx.coroutines.Dispatchers
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/4/12
 *
 * 获取用户手机号码Domain
 * 部分功能需要获取到用户自己的手机号做某些操作（例如修改密码、修改手机号）
 * 传入[Nothing]
 * 返回[String] 手机号
 */
class UserPhoneDataUseCase @Inject constructor(
    private val userCore: UserCore,
    private val userRepository: UserRepository
): SuspendUseCase<Nothing?, String>(
    Dispatchers.IO
){
    override suspend fun execute(parameters: Nothing?): Resource<String> {
        val userInfo = userCore.userInfo.value
        val isLogin = userCore.isLogin.value

        if(!isLogin || userInfo.userToken.isNullOrEmpty() || userInfo.userId.isNullOrEmpty()){
            return Resource.Error(ApiError.unknownCode,"非法操作")
        }
        return when(val result = userRepository.getDetailUserInfo(userInfo.userToken)){
            is ApiResult.Success -> {
                result.data.data?.phone?.let {
                    Resource.Success(it)
                } ?: Resource.Error(ApiError.serverErrorCode,"未知错误")
            }
            is ApiResult.Failure -> {
                Resource.Error(result.errorCode,result.errorMsg)
            }
            else -> {
                Resource.Error(ApiError.serverErrorCode,"未知错误")
            }
        }
    }
}